package wechat

import (
	"strings"
	"time"

	. "gddgame.cc/galaxy/common/dsl/web"
	"gddgame.cc/galaxy/utils/def"
)

func ReceiveWechat(context def.Context, talker string, message string) (interface{}, error) {
	var wechat WechatRobot
	var err error
	var ok bool
	now := time.Now()
	if ok, _ = WechatRobotModel.PK(talker).One(&wechat); !ok {
		wechat.Name = talker
		wechat.Talker = talker
		wechat.LastTime = &now
		wechat.IsChatroom = strings.HasSuffix(talker, "@chatroom")
		wechat.Status = true
		if _, err = WechatRobotModel.Insert(&wechat); err != nil {
			return nil, SystemExceptionDetail("添加失败", err)
		}
	}
	if wechat.IsChatroom {
		messages := strings.Split(message, ":")
		message = strings.TrimSpace(messages[1])
	}
	var response map[string]interface{}
	wechat.LastTime = &now
	switch message {
	case "开启":
		wechat.Status = true
		response = map[string]interface{}{
			"talker":  talker,
			"message": "开启成功",
		}
	case "关闭":
		wechat.Status = false
		response = map[string]interface{}{
			"talker":  talker,
			"message": "关闭成功",
		}
	case "刷新":

	}
	if _, err = WechatRobotModel.PK(wechat.Talker).Save(false, &wechat); err != nil {
		return nil, SystemExceptionDetail("更新失败", err)
	}
	return response, nil
}
func PopWechat(context def.Context) (interface{}, error) {
	var wechatMessage WechatMessage
	next := 30
	response := make(map[string]interface{})
	response["next"] = next

	l, err := WechatMessageModel.Query().
		Where("null", "send_time", nil).
		Order("id", "desc").
		FindAndCount(&wechatMessage, 1, 1)
	if err != nil {
		return nil, SystemExceptionDetail("消息队列错误", err)
	}

	context.Debugf("[ Wechat ] Pop Queue length: %d", l)
	if l > 0 {
		if int(l) > next {
			response["next"] = 1
		} else {
			response["next"] = 30 / l
		}
		context.Debugf("[ Wechat ] Pop Queue next: %d", response["next"])
		response["talker"] = wechatMessage.Talker
		response["message"] = wechatMessage.Message
		now := time.Now()
		_, _ = WechatMessageModel.PK(wechatMessage.Id).Update(map[string]interface{}{
			"send_time": &now,
		})
		context.Debugf("[ Wechat ] Pop Queue message: %s", response)
	}
	return response, nil
}
func PushWechat(context def.Context, talker string, message string) error {
	var wechat WechatRobot
	var err error
	var ok bool
	if ok, err = WechatRobotModel.PK(talker).One(&wechat); !ok {
		context.Debugf("[ Wechat ] Push %s, talker not exist", talker)
		return EmptyExceptionDetail("Talker不存在", err)
	}
	if !wechat.Status {
		// 过滤消息
		context.Debugf("[ Wechat ] Push %s, status filter", talker)
		return nil
	}
	wechatMessage := WechatMessage{
		Talker:  talker,
		Message: message,
	}
	context.Debugf("[ Wechat ] Push %s in Queue", talker)
	_, err = WechatMessageModel.Query().Save(true, &wechatMessage)
	return err
}
